package com.wang.nowcoder.service;

import com.wang.nowcoder.dao.LoginTicketMapper;
import com.wang.nowcoder.dao.UserMapper;
import com.wang.nowcoder.pojo.LoginTicket;
import com.wang.nowcoder.pojo.User;
import com.wang.nowcoder.util.CommunityConstant;
import com.wang.nowcoder.util.CommunityUtil;
import com.wang.nowcoder.util.MailClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author wang
 * @ClassName UserService
 * @Description TODO
 * @date 2021/12/13 11:30
 * @Version 1.0
 */
@Service
public class UserService implements CommunityConstant {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private LoginTicketMapper loginTicketMapper;


    @Value("${community.path.domain}")
    private String domain;


    /**
     * 根据ID查询用户
     * @param id
     * @return
     */
    public User selectById(int id){
        return userMapper.selectById(id);
    }

    /**
     * 根据姓名查询用户
     * @param userName
     * @return
     */
    public User selectByName(String userName){
        return userMapper.selectByName(userName);
    }

    /**
     * 根据邮箱查询
     * @param email
     * @return
     */
    public User selectByEmail(String email){
        return userMapper.selectByEmail(email);
    }

    /**
     * 增加一个用户
     * @param user
     * @return
     */
    public int insertUser(User user){
        return userMapper.insertUser(user);
    }

    /**
     * 更新用户状态
     * @param id
     * @param status
     * @return
     */
    public int updateStatus(int id,int status){
        return userMapper.updateStatus(id,status);
    }

    /**
     * 更新用户头像路径
     * @param id
     * @param headerUrl
     * @return
     */
    public int updateHeader(int id,String headerUrl){
        return userMapper.updateHeader(id, headerUrl);
    }

    /**
     * 更新密码
     * @param id
     * @param password
     * @return
     */
    public int updatePassword(int id,String password){
        return userMapper.updatePassword(id, password);
    }

    /**
     * 验证注册信息是否合法
     * @param user
     * @return
     */
    public Map<String,Object> register(User user){
        Map<String,Object> map = new HashMap<>();
        //空值判断
        if (user == null){
            throw new IllegalArgumentException("参数不能为空");
        }
        if (StringUtils.isBlank(user.getUserName())){
            map.put("userNameMsg","账号不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg","密码不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())){
            map.put("EmailMsg","邮箱不能为空");
            return map;
        }

        //验证账号
        User user1 = userMapper.selectByName(user.getUserName());
        if (user1!=null){
            map.put("userNameMsg","账号已存在");
            return map;
        }
        //验证邮箱
        user1 = userMapper.selectByEmail(user.getEmail());
        if (user1!=null){
            map.put("emailMsg","该邮箱已被注册");
            return map;
        }

        //注册用户
        //截取随机生成的字符串的五位
        user.setSalt(CommunityUtil.generateUUID().substring(0,5));
        //对密码进行加密
        user.setPassword(CommunityUtil.md5(user.getPassword()+user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        //设置激活码
        user.setActivationCode(CommunityUtil.generateUUID());
        //给新注册用户一个随机头像
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png",new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        //给用户发激活邮件
        Context context = new Context();
        context.setVariable("email",user.getEmail());
        //规定邮件路径:http://localhost/activation/101/code
        String url = domain+"/activation/"+user.getId()+"/"+user.getActivationCode();
        context.setVariable("url",url);
        String content = templateEngine.process("mail/activation",context);
        mailClient.sendMail(user.getEmail(),"激活账号",content);

        return map;
    }

    /**
     * 判断账号是否被激活
     * @param userId
     * @param code
     * @return
     */
    public int activation(int userId,String code){
        User user = userMapper.selectById(userId);
        if (user.getStatus() == 1){
            return ACTIVATION_REPEAT;
        }else if (user.getActivationCode().equals(code)){
            userMapper.updateStatus(userId,1);
            return ACTIVATION_SUCCESS;
        }else {
            return ACTIVATION_FAILURE;
        }
    }

    /**
     * 登录
     * @param userName
     * @param password
     * @param expiredSeconds
     * @return
     */
    public Map<String ,Object> login(String userName,String password ,long expiredSeconds){
        Map<String ,Object> map = new HashMap<>();

        //进行空值处理
        if (StringUtils.isBlank(userName)){
            map.put("userNameMsg","账号不能为空");
            return map;
        }
        if (StringUtils.isBlank(password)){
            map.put("passwordMsg","密码不能为空");
            return map;
        }

        //验证账号
        User user = userMapper.selectByName(userName);
        if (user == null){
            map.put("userNameMsg","该账号不存在");
            return map;
        }
        //判断账号是否激活
        if(user.getStatus() == 0){
            map.put("userNameMsg","账号未激活");
            return map;
        }
        //验证密码
        password = CommunityUtil.md5(password+user.getSalt());
        if (!user.getPassword().equals(password)){
            map.put("passwordMsg","密码错误");
            return map;
        }
        //生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds*1000));
        loginTicketMapper.insertLoginTicket(loginTicket);

        map.put("ticket",loginTicket.getTicket());
        return map;
    }

    /**
     * 退出
     * @param ticket
     */
    public void loginOut(String ticket){
        loginTicketMapper.updateStatus(ticket,1);
    }

    /**
     * 根据ticket查看用户
     * @param ticket
     * @return
     */
    public LoginTicket findLoginTicket(String ticket){
        return loginTicketMapper.selectByTicket(ticket);
    }

}
